﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace WFL.Utils
{
    public static class MD5Helper
    {
        public static byte[] Compute(string filePath)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                return Compute(fs);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }

        public static byte[] Compute(Stream stream)
        {
            MD5CryptoServiceProvider md5 = null;
            try
            {
                md5 = new MD5CryptoServiceProvider();
                return md5.ComputeHash(stream);
            }
            finally
            {
                if (md5 != null)
                {
                    md5.Clear();
                }
            }
        }

        public static byte[] Compute(byte[] bytes)
        {
            MD5CryptoServiceProvider md5 = null;
            try
            {
                md5 = new MD5CryptoServiceProvider();
                return md5.ComputeHash(bytes);
            }
            finally
            {
                if (md5 != null)
                {
                    md5.Clear();
                }
            }
        }

        public static string ComputeHex(string filePath)
        {
            return FormatBytesToHex(Compute(filePath));
        }

        public static string ComputeHex(Stream stream)
        {
            return FormatBytesToHex(Compute(stream));
        }

        public static string ComputeHex(byte[] bytes)
        {
            return FormatBytesToHex(Compute(bytes));
        }

        private static string FormatBytesToHex(byte[] bytes)
        {
            StringBuilder sb = new StringBuilder(bytes.Length * 2);
            for (int i = 0; i < bytes.Length; i++)
            {
                sb.Append(bytes[i].ToString("x2"));
            }
            return sb.ToString();
        }
    }
}
